from datetime import datetime, timedelta
import sys
import urllib
import random
from optparse import OptionParser

from web.service.HttpReader import HttpReader, HttpReadError

usage = "usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--iterations", dest="iters", help="Number of test iterations", type=int, default=1000)
(options, args) = parser.parse_args()

streets_ba = open('streets_ba.txt', 'r')
streets = streets_ba.read().split('\n')
streets_ba.close()
num_streets = len(streets)


log_file = open('frontend_tester.log', 'w+')

iters = options.iters

while iters > 0:
    result = ''
    start = datetime.now()
    try:        
        loc_a_st = streets[random.randint(0, num_streets - 1)]
        loc_b_st = streets[random.randint(0, num_streets - 1)]
        while loc_b_st == loc_a_st:
            loc_b_st = streets[random.randint(0, num_streets - 1)]
        loc_a_num = random.randint(1, 50)
        loc_b_num = random.randint(1, 50)
        
        loc_a = '%s %s' % (loc_a_st, loc_a_num)
        loc_b = '%s %s' % (loc_b_st, loc_b_num)
                    
        url = 'http://localhost:8000/elvira/find_route?a=%s&b=%s' % (urllib.quote_plus(loc_a), 
                                                                     urllib.quote_plus(loc_b)) 
         
        httpReader = HttpReader()        
        status = 'OK'
        data = httpReader.read(url = url)
        if data.find('no route') != -1:
            status = 'ERR (no route)'
            
        
        end = datetime.now()
        
        result = '[%s (%d)]\t%s\t{from:%s\tto:%s}\n' % (start, (end - start).seconds, status, loc_a, loc_b) 
        
    except HttpReadError, e:
        end = datetime.now()
        result = '[%s (%d)]\tERR (%s)\t{from:%s\tto:%s}\n' % (start, (end - start).seconds, e, loc_a, loc_b)                
    except Exception, e:
        end = datetime.now()
        result = '[%s (%d)]\tERR (%s)\t{from:%s\tto:%s}\n' % (start, (end - start).seconds, e, loc_a, loc_b)
        
                
    log_file.write(result)
    log_file.flush()
    
    iters = iters - 1

log_file.close()